layui.use(['element', 'layer', 'form', 'table'], function () {
    var element = layui.element;
    var table = layui.table;
    var layer = layui.layer;
    var form = layui.form;
    var myCloudId = $('#cloudId').text();
    var id;

    var tableInfo = table.render({
        id: 'houseInfoTableId',
        elem: '#houseInfoTable',
        url: '/admin/houseInfo/houseInfoDetail',
        method: 'post',
        where:{
            cloudId:myCloudId
        },
        page: true,
        limit: 10,
        loading: true,
        skin: 'row',
        even: true,
        text: {
            none: '暂无相关数据'
        },
        cols: [[
            {checkbox: true, fixed: true},
            {field: 'id', title: '房子ID', fixed: 'left'}
            , {field: 'cloudId', title: '云图ID', sort: true, unresize: true, width: 80}
            , {field: 'userId', title: '发布者', align: 'center'}
            , {field: 'phone', title: '电话'}
            , {field: 'expireTime', title: '过期时间', align: 'center'}
            , {field: 'statusStr', title: '状态', unresize: true, align: 'center', width: 80}
            , {field: 'createTime', title: '创建时间', sort: true, unresize: true, align: 'center'}
            , {fixed: 'right', title: '操作', width: 150, align: 'center', unresize: true, toolbar: '#oreationBtn'}
        ]]
    });

    table.on('tool(houseInfoTable)', function (obj) {
        var layEvent = obj.event;////获得 lay-event 对应的值
        if (layEvent === 'detail') { //详情
            detailFunction(obj);
        } else if (layEvent === 'del') { //删除
            deleteFunction(obj);
        } else if (layEvent === 'update') { //更新
            updateFunction(obj);
        }
    });

    function detailFunction(obj) {
        if (obj.data.detailInfo == null) {
            layer.msg("暂无详情");
            return;
        }
        id = obj.data.id;
        var detailData = JSON.parse(obj.data.detailInfo);
        var conetnt = $('#houseDetail');
        layer.open({
            type: 1,
            skin: 'layui-layer-molv',
            title: ['房东: '+obj.data.userId+" =============  联系电话:  "+obj.data.phone, 'font-size:18px;'],
            closeBtn: 1,
            shade: 0,
            content: conetnt,
            area: ['100%', '100%'],
            shadeClose: true,
            resize: true,
            anim: 1,
            id: 'LAY_layuidetail23454',
            moveType: 1,
            maxmin: false,
            success: function (layero, index) {
                $('#openSwitch').prop('checked',false);
                $('#uploadDiv').hide();
                $('#detail_confirmbtn').hide();
                $('#detail_houseName').val(detailData.houseName);
                $('#detail_address').val(detailData.address);
                $('#detail_price').val(detailData.price);
                $('[name="detail_type"][value="' + detailData.type + '"]').prop('checked', true);
                $('#detail_select_houseType').val(detailData.houseType);
                $('#detail_select_renovation').val(detailData.renovation);
                $('#detail_txt').val(detailData.txt);
                $('#detail_waterRate').val(detailData.metaData.waterRate);
                $('#detail_electricityFee').val(detailData.metaData.electricityFee);
                $('#detail_extralFee').val(detailData.metaData.extralFee);
                var extralData = detailData.metaData.additionalAttr.split(',');
                extralData.forEach(function (value) {
                    $('input:checkbox[name="detail_extralData"][value="' + value + '"]').prop('checked', true);
                });
                var photos = detailData.photos.data;
                $('#photoItem').attr("carousel-item",photos.length);
                photos.forEach(function (val) {
                    $('#photoItem').append('<div><img src="'+ val.src +'"</div>')
                });
                layui.use('carousel', function(){
                    var carousel = layui.carousel;
                    carousel.render({
                        elem: '#photos'
                        ,width: '100%' //设置容器宽度
                        ,arrow: 'none' //显示箭头
                        ,anim: 'fade' //切换动画方式
                    });
                });
                form.render();
                form.on('switch(isUpdate)', function(data){
                    if (data.elem.checked) {
                        $('#uploadDiv').show();
                        $('#detail_confirmbtn').show();
                    }else {
                        $('#uploadDiv').hide();
                        $('#detail_confirmbtn').hide();
                    }
                });
            },
            cancel: function (index, layero) {
                $('#photoItem').html('');
            }
        });
    }

    function deleteFunction(obj) {
        layer.open({
            type: 1,
            title: false,
            closeBtn: 2,
            resize: true,
            content: '<div style="padding: 50px; line-height: 22px; background-color: #393D49; color: #fff; font-weight: 300;">' +
            '(请慎重)是否需要删除?删除后将不可恢复</div>',
            area: '30%',
            shade: 0.8,
            shadeClose: true,
            anim: 1,
            id: 'LAY_layuiprodel', //设定一个id，防止重复弹出
            btn: ['绝不后悔', '我怂了'],
            moveType: 1,
            yes: function (index, layero) {
                var params = $.param({
                    id: obj.data.id
                }, true);
                $.ajax({
                    url: '/admin/houseInfo/deleteById',
                    type: 'post',
                    data: params,
                    dataType: 'json',
                    success: function (e) {
                        layer.msg(e.msg);
                        layer.close(index);
                        if (e.msg == "删除成功") {
                            obj.del();
                        }
                    }
                })
            }
        });
    }
    
    function updateFunction(obj) {
        var content = $('#updateProperty');
        $('#updateInfo').text('确认更新');
        layer.open({
            type: 1,
            skin: 'layui-layer-molv',
            title: ['更新基本数据', 'font-size:18px;'],
            closeBtn: 1,
            shade: 0.3,
            content: content,
            area: ['50%', '60%'],
            shadeClose: true,
            resize: true,
            anim: 1,
            id: 'LAY_layuiroupdate', //设定一个id，防止重复弹出
            moveType: 1,
            maxmin: false,
            success: function (layero, index) {
                $('#expireTimeScopeId').hide();
                $('#expireTimeId').show();
                $('#userId').val(obj.data.userId);
                $('#phone').val(obj.data.phone);
                $('#expireTime').val(obj.data.expireTime);
                $('#status').val(obj.data.status);
                form.render();
                var active = {
                    updateInfo:function () {
                        var userId =  $('#userId').val();
                        var phone =  $('#phone').val();
                        var expireTime =  $('#expireTime').val();
                        var status =  $('#status').val();
                        var statusStr = $('#status option:selected').text();
                        if (userId == '' || phone == '' || expireTime =='') {
                            layer.msg('数据不可为空');
                            return false;
                        }
                        if(userId == obj.data.userId &&  phone == obj.data.phone
                            && expireTime ==obj.data.expireTime && status == obj.data.status) {
                            layer.msg('未做任何修改');
                            return false;
                        }
                        var params = $.param({
                            id:obj.data.id,
                            userId: userId,
                            phone: phone,
                            expireTime: expireTime,
                            status: status
                        }, true);
                        $.ajax({
                            url: '/admin/houseInfo/updateProperty',
                            type: 'post',
                            data: params,
                            dataType: 'json',
                            success: function (e) {
                                layer.msg(e.msg);
                                layer.close(index);
                                if (e.msg == "更新成功") {
                                    //同步更新缓存对应的值
                                    obj.update({
                                        userId: userId,
                                        phone: phone,
                                        expireTime:expireTime,
                                        statusStr: statusStr,
                                        status:status
                                    });
                                }
                            }
                        })
                    },
                    resetInfo:function () {
                        $('#userId').val('');
                        $('#phone').val('');
                        $('#expireTime').val('');
                        $('#status').val(0);
                        form.render();
                    }
                };
                $('.updateProperty .layui-btn').on('click', function () {
                    var type = $(this).data('type');
                    active[type] ? active[type].call(this) : '';
                });
            },
            cancel: function(index, layero){
                $('#userId').val('');
                $('#phone').val('');
                $('#expireTime').val('');
                $('#status').val(0);
                form.render();
            }
        })
    }

    //批量删除
    var active = {
        deleteHouseInfo: function () {
            var checkStatus = table.checkStatus('houseInfoTableId')
                , data = checkStatus.data;
            if (data.length > 50) {
                layer.msg("超过最大数量限制");
                return false;
            }
            layer.open({
                type: 1,
                title: false,
                closeBtn: 2,
                resize: true,
                content: '<div style="padding: 50px; line-height: 22px; background-color: #393D49; color: #fff; font-weight: 300;">' +
                '是否需要删除?删除后将不可恢复</div>',
                area: '30%',
                shade: 0.8,
                shadeClose: true,
                anim: 1,
                id: 'LAY_layuiprodel', //设定一个id，防止重复弹出
                btn: ['绝不后悔', '我怂了'],
                moveType: 1,
                yes: function (index, layero) {
                    var params = $.param({
                        mydata: JSON.stringify(data)
                    }, true);
                    $.ajax({
                        url: '/admin/houseInfo/deleteBatchById',
                        type: 'post',
                        data: params,
                        dataType: 'json',
                        success: function (e) {
                            layer.msg(e.msg);
                            layer.close(index);
                            if (e.msg == "删除成功") {
                                tableInfo.reload({ //执行重载
                                    page: {
                                        curr: 1 //重新从第 1 页开始
                                    },
                                    where:{
                                        cloudId:myCloudId
                                    },
                                    done: function (res, curr, count) {
                                        this.where = {};
                                    }
                                });
                            }
                        }
                    })
                }
            });
        },
        findHouseInfo:function () {
            var content = $('#updateProperty');
            layer.open({
                type: 1,
                skin: 'layui-layer-molv',
                title: ['查询基本数据', 'font-size:18px;'],
                closeBtn: 1,
                shade: 0.3,
                content: content,
                area: ['50%', '60%'],
                shadeClose: true,
                resize: true,
                anim: 1,
                id: 'LAY_layuiroupFind',
                moveType: 1,
                maxmin: false,
                success: function (layero, index) {
                    $('#updateInfo').text('查询');
                    $('#expireTimeScopeId').show();
                    $('#expireTimeId').hide();
                    $('#userId').val('');
                    $('#phone').val('');
                    $('#expireTimeScopeId').val('');
                    $('#status').val(0);
                    form.render();
                    var active = {
                        updateInfo:function () {
                            var userId =  $('#userId').val();
                            var phone =  $('#phone').val();
                            var expireTimeScope =  $('#expireTimeScope').val();
                            var status =  $('#status').val();
                            var params = {
                                userId: userId,
                                phone: phone,
                                expireTimeScope: expireTimeScope,
                                status: status,
                                cloudId:myCloudId
                            };
                            tableInfo.reload({
                                where: {
                                    key: JSON.stringify(params) //转成json
                                },
                                page: {
                                    curr: 1 //重新从第 1 页开始
                                },
                                done: function (res, curr, count) {
                                    this.where = {};
                                    layer.close(layer.index);
                                }
                            });
                        },
                        resetInfo:function () {
                            $('#userId').val('');
                            $('#phone').val('');
                            $('#expireTimeScopeId').val('');
                            $('#status').val(0);
                            form.render();
                        }
                    };
                    $('.updateProperty .layui-btn').on('click', function () {
                        var type = $(this).data('type');
                        active[type] ? active[type].call(this) : '';
                    });
                },
                cancel: function(index, layero){
                    $('#userId').val('');
                    $('#phone').val('');
                    $('#expireTimeScopeId').hide();
                    $('#expireTimeId').show();
                    $('#expireTimeScopeId').val('');
                    $('#status').val(0);
                    form.render();
                }
            })
        },
        confirmHousebtn:function () {
            var userId = $('#myuserId').val();
            var phone = $('#myphone').val();
            var houseName = $('#houseName').val();
            var address = $('#address').val();
            var price = $('#price').val();
            var type = $('input[name="type"]:checked').val();
            var houseType = $('#select_houseType').val();
            var renovation = $('#select_renovation').val();
            var txt = $('#txt').val();
            var waterRate = $('#waterRate').val();
            var electricityFee = $('#electricityFee').val();
            var extralFee = $('#extralFee').val();
            var duiringTime = $('#duiringTime').val();
            var extralData = '';
            $('input[name="extralData"]:checked').each(function(){
                extralData += $(this).val();
                extralData += ','
            });
            if (userId == '' || phone == '' || houseName == '' || address == '' ||
                price == '' || txt == '' || waterRate == '' || electricityFee == '' ||
                extralFee == '' || duiringTime == '' || extralData == '') {
                layer.msg("请先填写完整信息");
                return false;
            }

            var params={
                userId:userId,
                phone:phone,
                cloudId:myCloudId,
                duiringTime:duiringTime,
                houseName:houseName,
                address:address,
                price:price,
                type:type,
                houseType:houseType,
                renovation:renovation,
                txt:txt,
                waterRate:waterRate,
                electricityFee:electricityFee,
                extralFee:extralFee,
                extralData:extralData
            };
            $.ajax({
                url:'/admin/houseInfo/addOrUpdateHouseDetail',
                type:'post',
                data:params,
                dataType:'json',
                success:function (e) {
                    layer.msg(e.msg);
                    if (e.msg == '添加成功') {
                        $('#myuserId').val('');
                        $('#myphone').val('');
                        $('#houseName').val('');
                        $('#address').val('');
                        $('#price').val('');
                        $('[name="type"][value="' + 0 + '"]').prop('checked', true);
                        $('#select_houseType').val(0);
                        $('#select_renovation').val(0);
                        $('#txt').val('');
                        $('#waterRate').val('');
                        $('#electricityFee').val('');
                        $('#extralFee').val('');
                        $('#duiringTime').val('10');
                        form.render();
                        tableInfo.reload({ //执行重载
                            page: {
                                curr: 1 //重新从第 1 页开始
                            },
                            where:{
                                cloudId:myCloudId
                            },
                            done: function (res, curr, count) {
                                this.where = {};
                            }
                        });
                    }
                }
            });
        },
        detail_updateDetail:function(){
            var houseName = $('#detail_houseName').val();
            var address = $('#detail_address').val();
            var price = $('#detail_price').val();
            var type = $('input[name="detail_type"]:checked').val();
            var houseType = $('#detail_select_houseType').val();
            var renovation = $('#detail_select_renovation').val();
            var txt = $('#detail_txt').val();
            var waterRate = $('#detail_waterRate').val();
            var electricityFee = $('#detail_electricityFee').val();
            var extralFee = $('#detail_extralFee').val();
            var extralData = '';
            $('input[name="detail_extralData"]:checked').each(function(){
                extralData += $(this).val();
                extralData += ','
            });
            if (houseName == '' || address == '' ||
                price == '' || txt == '' || waterRate == '' || electricityFee == '' ||
                extralFee == '' ||  extralData == '') {
                layer.msg("请先填写完整信息");
                return false;
            }
            var params={
                id:id,
                houseName:houseName,
                address:address,
                price:price,
                type:type,
                houseType:houseType,
                renovation:renovation,
                txt:txt,
                waterRate:waterRate,
                electricityFee:electricityFee,
                extralFee:extralFee,
                extralData:extralData
            };
            $.ajax({
                url:'/admin/houseInfo/addOrUpdateHouseDetail',
                type:'post',
                data:params,
                dataType:'json',
                success:function (e) {
                    layer.msg(e.msg);
                    setTimeout(function () {
                        if (e.msg == '更新成功' ) {
                            tableInfo.reload({ //执行重载
                                page: {
                                    curr: 1 //重新从第 1 页开始
                                },
                                where:{
                                    cloudId:myCloudId
                                },
                                done: function (res, curr, count) {
                                    this.where = {};
                                }
                            });
                            var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                            parent.layer.close(index); //再执行关闭
                        }
                    },2000);
                }
            });
        }
    };

    //全局操作按钮
    $('.AllBtnController .layui-btn').on('click', function () {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });

    $('.confirmHouse .layui-btn').on('click', function () {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });

    $('.confirmUpdateHouse .layui-btn').on('click', function () {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });

    layui.use('laydate', function () {
        var laydate = layui.laydate;
        laydate.render({
            elem: '#expireTime'
            ,type: 'datetime'
        });
    });

    layui.use('laydate', function () { //日期
        var laydate = layui.laydate;
        laydate.render({
            elem: '#expireTimeScope',
            type: 'datetime',
            range: true,
            format: 'yyyy-MM-dd HH:mm:ss',
            calendar: true
        });
    });

    layui.use('upload', function(){
        var $ = layui.jquery,upload = layui.upload;
        upload.render({
            elem:'#batchUpload',
            url:'/admin/houseInfo/batch/upload',
            accept:'images',
            multiple: true,
            auto: false,
            bindAction:'#confirmUpload',
            choose:function(obj) {
                obj.preview(function(index, file, result){
                    $('#showList').append('<img src="'+ result +'" alt="'+ file.name +'" class="layui-upload-img" style="width: 200px; height: 200px;">&nbsp;&nbsp;&nbsp;&nbsp;')
                });
            },
            allDone: function(obj) {
                layer.msg(obj.successful+"个文件上传成功");
                if (obj.aborted > 0)
                    layer.msg(obj.aborted + "个文件上传失败");
            },
            done: function(res){
            }
        })
    });

    layui.use('upload', function(){
        var $ = layui.jquery,upload = layui.upload;
        upload.render({
            elem:'#detail_batchUpload',
            url:'/admin/houseInfo/batch/upload',
            accept:'images',
            multiple: true,
            auto: false,
            bindAction:'#detail_confirmUpload',
            choose:function(obj) {
                obj.preview(function(index, file, result){
                    $('#detail_showList').append('<img src="'+ result +'" alt="'+ file.name +'" class="layui-upload-img" style="width: 200px; height: 200px;">&nbsp;&nbsp;&nbsp;&nbsp;')
                });
            },
            allDone: function(obj) {
                layer.msg(obj.successful+"个文件上传成功");
                if (obj.aborted > 0)
                    layer.msg(obj.aborted + "个文件上传失败");
            },
            done: function(res){
            }
        })
    });
});